/*
 * @Author: Cumelmell
 * @Date: 2020-04-27 17:02:07
 * @LastEditors: Cumelmell
 * @LastEditTime: 2020-05-17 01:07:22
 */
import { getUserInfo } from '@/api/user';
import { menuName } from '@/utils';

const getDefaultState = () => {
  return {
    name: '',
    avatar: '',
    roles: [],
    isLogin: false,
    userid: '',
    userInfo: {}
  };
};

const state = {
  token: '',
  department: '',
  warehouse: [], // 仓库
  menus: [], // 菜单/权限
  userInfo: getDefaultState()
};

const mutations = {
  setUserInfo (state, result) {
    const { data } = result;
    state.userInfo = data;
    state.token = result.token;
    state.department = _.get(data, 'department[0].department_name');
    // state.dept_id = _.get(data, 'department[0].dept_id');
    state.dept_id = data.department.map(item => item.dept_id).join(',');
    state.departmentList = data.department;
    state.warehouse = _.get(data, 'warehouse');
    state.menus = menuName(_.get(data, 'menu') || []);
    state.isLogin = true;
  },
  resetToken (state) {
    state.token = '';
  }
};

const actions = {
  getUserInfo ({ commit }, payload) {
    return new Promise((resolve, reject) => {
      getUserInfo(payload).then(res => {
        if (res.code === 0) {
          commit('setUserInfo', res.result);
          resolve(true);
        }
      }).catch(err => reject(err));
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
